package com.leisurexi.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * Nio 阻塞式服务端
 *
 * @author: leisurexi
 * @date: 2021-01-05 22:57
 */
public class BlockServer {

    public static void main(String[] args) {

        try (
                // 1. 获取 socket 通道
                ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                // 2. 得到文件通道，不存在自动创建
                FileChannel fileChannel = FileChannel.open(Paths.get("C:\\Users\\lwx\\Desktop\\goddess.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE)
        ) {
            // 3. 绑定端口
            serverSocketChannel.bind(new InetSocketAddress(8888));
            // 4. 获取客户端的连接
            SocketChannel clientChannel = serverSocketChannel.accept();
            // 5. 创建 buffer 用于接收数据
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            // 6. 读取客户端传过来的数据
            while (clientChannel.read(buffer) != -1) {
                // 切换为读模式
                buffer.flip();
                fileChannel.write(buffer);
                // 清空 buffer 准备下一次写入数据
                buffer.clear();
            }

            // 回复客户端接收成功
            buffer.put("SUCCESS".getBytes());
            buffer.flip();
            clientChannel.write(buffer);
            buffer.clear();

            // 关闭客户端连接
            clientChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
